package com.example.medicalequipment.controller;

import android.content.Context;
import android.os.AsyncTask;

import androidx.annotation.Nullable;

import com.example.medicalequipment.database.AppDatabase;
import com.example.medicalequipment.entity.User;

public class UserController {

    private AppDatabase database;

    public UserController(Context context) {
        database = AppDatabase.getInstance(context);
    }

    public void register(final User user, final RegisterCallback callback) {
        new AsyncTask<Void, Void, Long>() {
            @Override
            protected Long doInBackground(Void... voids) {
                // 检查用户名是否已存在
                User existingUser = database.userDao().getUserByUsername(user.getUsername());
                if (existingUser != null) {
                    return -1L; // 用户名已存在
                }
                return database.userDao().insertUser(user);
            }

            @Override
            protected void onPostExecute(Long result) {
                if (callback != null) {
                    callback.onRegisterResult(result);
                }
            }
        }.execute();
    }

    public void login(final String username, final String password, final LoginCallback callback) {
        new AsyncTask<Void, Void, User>() {
            @Override
            protected User doInBackground(Void... voids) {
                return database.userDao().login(username, password);
            }

            @Override
            protected void onPostExecute(User user) {
                if (callback != null) {
                    callback.onLoginResult(user);
                }
            }
        }.execute();
    }

    public void getUserById(final int id, final GetUserCallback callback) {
        new AsyncTask<Void, Void, User>() {
            @Override
            protected User doInBackground(Void... voids) {
                return database.userDao().getUserById(id);
            }

            @Override
            protected void onPostExecute(User user) {
                if (callback != null) {
                    callback.onGetUserResult(user);
                }
            }
        }.execute();
    }

    public interface RegisterCallback {
        void onRegisterResult(long result);
    }

    public interface LoginCallback {
        void onLoginResult(@Nullable User user);
    }

    public interface GetUserCallback {
        void onGetUserResult(@Nullable User user);
    }
}
